package com.linkgie.galaxyframework.web.client;

import java.io.InputStream;

import com.linkgie.galaxyframework.httpproxy.HttpServiceContext;
import com.linkgie.galaxyframework.httpproxy.ResponseConverter;
import com.linkgie.galaxyframework.httpproxy.converters.JsonResponseConverter;
import com.linkgie.galaxyframework.httpproxy.core.ServiceRequest;
import com.linkgie.galaxyframework.utils.json.JsonElement;
import com.linkgie.galaxyframework.utils.lang.DataTypeUtils;
import com.linkgie.galaxyframework.web.ServiceResponse;

/**
 * Web 接口的返回值转换器；
 * <p>
 * 已经在版本 2.8.9.RELEASE 中被废弃，请使用 {@link ServiceResponseHandler} 代替；
 */
@Deprecated
public class ServiceResponseConverter implements ResponseConverter {

	private JsonResponseConverter jsonConverter = new JsonResponseConverter(ServiceResponse.class);

	private Class<?> dataClazz;

	public ServiceResponseConverter(Class<?> dataClazz) {
		this.dataClazz = dataClazz;
	}

	@Override
	public Object getResponse(ServiceRequest request, InputStream responseStream, HttpServiceContext serviceContext)
			throws Exception {
		ServiceResponse<?> response = (ServiceResponse<?>) jsonConverter.getResponse(request, responseStream, null);
		if (response == null) {
			return null;
		}
		if (!response.isSuccess()) {
			throw new ServiceResponseException(response.getStatus(), response.getMessage());
		}

		// 由于 response.data 声明为 Object 类型，实际返回类型为 JsonElement ；
		Object responseData = response.getData();
		if (responseData == null) {
			if (dataClazz.isPrimitive()) {
				// 针对基本类型，如果返回 null ，由于无法转换，所以报告异常；
				throw new IllegalStateException("Declared a primitive return type but received null response data!");
			}
			return null;
		}
		if (dataClazz.isAssignableFrom(responseData.getClass())) {
			return responseData;
		}
		if (dataClazz.isAssignableFrom(String.class)) {
			return responseData.toString();
		}
		if (DataTypeUtils.isPrimitiveType(dataClazz)) {
			// Object value = responseData.toValue(dataClazz);
			// 预期 responseData 实际也是基本类型，
			return DataTypeUtils.castTo(responseData, dataClazz);
		}
		if (responseData instanceof JsonElement) {
			return ((JsonElement) responseData).toValue(dataClazz);
		}
		throw new IllegalStateException("Cann't convert response data from type[" + responseData.getClass().getName()
				+ "] to required type[" + dataClazz.getName() + "]");
	}
}
